using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace NetSpider.Retrieval
{
    public class FileStoredContent : IContent
    {
        private bool _disposed = false;

        private readonly string _uri;
        private readonly string _contentType;
        private readonly string _contentFile;
        private byte[] _content = null;

        public FileStoredContent(string uri, string contentType, string contentFile)
        {
            _uri = uri;
            _contentType = contentType;
            _contentFile = contentFile;
        }

        public string ContentType
        {
            get
            {
                if (_disposed) throw new ObjectDisposedException(null);

                return _contentType;
            }
        }

        public long Length
        {
            get
            {
                if (_disposed) throw new ObjectDisposedException(null);

                return _content.Length;
            }
        }

        public byte[] GetContent()
        {
            if (_disposed) throw new ObjectDisposedException(null);

            if (_content == null)
            {
                if (File.Exists(_contentFile))
                {
                    using (Stream fileStream = File.Open(_contentFile, FileMode.Open))
                    {
                        _content = new byte[fileStream.Length];
                        fileStream.Read(_content, 0, _content.Length);
                    }
                }
                else
                {
                    throw new Exception();
                }
            }

            return _content;
        }

        public string GetText()
        {
            if (_disposed) throw new ObjectDisposedException(null);

            return TextHelper.DecodeText(_contentType, GetContent());
        }

        public void Fill(byte[] content)
        {
            if (_disposed) throw new ObjectDisposedException(null);

            _content = content;
        }

        public string Uri
        {
            get { return _uri; }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                FileHelper.DeleteFile(_contentFile);
                _disposed = true;
            }
        }

        ~FileStoredContent()
        {
            Dispose(false);
        }
    }
}